/*
 * Copyright (c) 2022 HiSilicon (Shanghai) Technologies CO., LIMITED.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include <string.h>
#include "iot_config.h"
#include "iot_main.h"
#include "iot_profile.h"
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "wifi_connecter.h"
#include "cjson_init.h"
#include "app_demo_iot.h"

#define TASK_SLEEP_1000MS (1000)
#define CN_COMMAND_INDEX                    "commands/request_id="

#if CHIP_WS63
#define STACK_SIZE 10240
#define MAX_CONNECT_RETRY_TIMES 16
#define CONNECT_ATTEMPT_INTERVAL_MS 300
#else
#define ATTR.STACK_SIZE 10240
#endif
#include "sle_uart_server.h"
// #include "cJSON.h"
#include <cJSON.h>
char MqttMsg[20] = {0};
char *const_water_in = "water_in";
static void DemoMsgRcvCallBack(int qos, char *topic, char *payload)
{
    const char *requesID;
    char *tmp;
    IoTCmdResp resp;
    printf("RCVMSG:QOS:%d TOPIC:%s PAYLOAD:%s\r\n", qos, topic, payload);
    //{"data":{"water_info":1},"method":"command.setProperty.exec","reqid":"0bb13438ae064e3c9960c95eae22e760","t":1725850713241,"v":"1"}
    // cJSON *root = cJSON_Parse(payload);
	// if (root == NULL)
	//     return;
	// cJSON *water_info = cJSON_GetObjectItem(root, "water_info");
    // if(water_info->valuestring[0]=="1")
    // {
    //     strncpy(MqttMsg, const_water_in, 8);
    //     sle_uart_server_send_report_by_handle(MqttMsg,strlen(MqttMsg));
    // }
    strncpy(MqttMsg, const_water_in, 8);
    sle_uart_server_send_report_by_handle(MqttMsg,strlen(MqttMsg));
    /* app 下发的操作 */
    //TrafficLightMsgRcvCallBack(payload);
    tmp = strstr(topic, CN_COMMAND_INDEX);
    if (tmp != NULL) {
        // /< now you could deal your own works here --THE COMMAND FROM THE PLATFORM
        // /< now er roport the command execute result to the platform
        requesID = tmp + strlen(CN_COMMAND_INDEX);
        resp.requestID = requesID;
        resp.respName = NULL;
        resp.retCode = 0;   ////< which means 0 success and others failed
        resp.paras = NULL;
        (void)IoTProfileCmdResp(CONFIG_DEVICE_PWD, &resp);
    }
}

/* traffic light:1.control module */
void IotPublishSample(void)
{
    char topic[] = "RSU";
    char msg[] = "{\"RSU_SLE\":\"RSU_SLE\"}";
    IotSendMsg(0, topic, msg);
}

static void WifiConnectToHost(int *arg)
{
    (void)arg;

    osDelay(10);

    // setup your AP params
    // 设置AP参数，包括SSID、预共享密钥、安全类型（PSK）、netID
    WifiDeviceConfig apConfig = {0};
    if (strcpy_s(apConfig.ssid, sizeof(apConfig.ssid), CONFIG_AP_SSID)) {
        printf("CONFIG_AP_SSID OK");
    }

    if (strcpy_s(apConfig.preSharedKey, sizeof(apConfig.preSharedKey), CONFIG_AP_PWD)) {
        printf("CONFIG_AP_PWD OK");
    }

    apConfig.securityType = WIFI_SEC_TYPE_PSK;

#if CHIP_WS63
    int netId = -1;

    // demo启动时，系统的WiFi功能可能没有初始化完毕，需要等待不确定的时候。待优化。
    for (uint8_t i = 0; i < MAX_CONNECT_RETRY_TIMES; i++) {
        osDelay(CONNECT_ATTEMPT_INTERVAL_MS);
        netId = ConnectToHotspot(&apConfig);
        if (netId >= 0) {
            break;
        }
    }
#else
    int netId = ConnectToHotspot(&apConfig);
#endif

    // 连接等待一定时间后自动断开
    // int timeout = 60;
    // while (timeout--) {
    //     printf("After %d seconds I will disconnect with AP!\r\n", timeout);
    //     osDelay(ONE_HUNDRED);
    // }
    // // 断开热点连接
    // DisconnectWithHotspot(netId);
}

// /< this is the demo main task entry,here we will set the wifi/cjson/mqtt ready ,and
// /< wait if any work to do in the while
static void DemoEntry(int *arg)
{
    WifiConnectToHost(arg);
    CJsonInit();
    IoTMain();
    IoTSetMsgCallback(DemoMsgRcvCallBack);
    TimeDelaySeconds(3);//TaskMsleep(30000); // 30000 = 3s连接华为云
/* 主动上报 */
    while (1) {
        // here you could add your own works here--we report the data to the IoTplatform
        TimeDelaySeconds(1);//TaskMsleep(TASK_SLEEP_1000MS);
        // know we report the data to the iot platform
        // IotPublishSample();
    }
}

// This is the demo entry, we create a task here, and all the works has been done in the demo_entry
#define CN_IOT_TASK_STACKSIZE  0x1000
#define CN_IOT_TASK_PRIOR 28
#define CN_IOT_TASK_NAME "AppDemoIot"
static void AppDemoIot(void)
{
    osThreadAttr_t attr;
    //IoTWatchDogDisable();
    attr.name = CN_IOT_TASK_NAME;
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = CN_IOT_TASK_STACKSIZE;
    attr.priority = CN_IOT_TASK_PRIOR;

    if (osThreadNew((osThreadFunc_t)DemoEntry, NULL, &attr) == NULL) {
        printf("Failed to create IOTDEMO!\n");
    } else {
        printf("IOTDEMO created successfully!\n");
    }
}

SYS_RUN(AppDemoIot);